package com.ody.util.code.generator;

import com.odianyun.util.ResourceUtils;
import com.odianyun.util.io.Closer;
import com.odianyun.util.io.FileUtils;
import com.ody.util.code.CodeContext;
import com.ody.util.code.PlaceHolderHelper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class FileCodeGenerator extends AbstractCodeGenerator {
	private String filename;
	private String targetDir;
    private boolean overridable;
    private boolean override;
    private boolean append;
	
	@Override
	protected void doGenerate(String content, CodeContext ctx, File tmplFile) throws Exception {
        ctx.set("filename", tmplFile.getName());
        ctx.set("filenameWithoutExt", FileUtils.getFilenameWithoutExtName(tmplFile.getName()));
		String filename = getFilename(ctx);
		String targetDir = getTargetDir(ctx);
        targetDir = targetDir.replaceAll("[.](?=[^./])", "/");
		
		writeFile(targetDir, filename, content);
	}

	protected void writeFile(String targetDir, String filename, String content) throws Exception {
		FileUtils.mkdir(new File(targetDir));
		
		String file = FileUtils.appendSeparatorSuffix(targetDir) + filename;
        File f = new File(file);
		
		if (! f.exists() || this.isOverride() || this.isAppend()) {
			logger.info(getName() + "-Write file [{}] to directory: {}",  filename, targetDir);
            
            doWriteFile(content, targetDir, file);
        }
	}
    
    protected void doWriteFile(String content, String targetDir, String file) throws Exception {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, this.isAppend()), getFileEncoding()));
        try {
            writer.write(content);
        } finally {
            Closer.close(writer);
        }
    }
    
    public void setTargetDir(String targetDir) {
		this.targetDir = targetDir;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
    
    protected String getTargetDir(CodeContext ctx) throws Exception {
	    String dir = PlaceHolderHelper.replace(targetDir, ctx.getCtxMap());
        System.out.printf("%s, %s\n", targetDir,  dir);
		return ResourceUtils.getResourcePath(dir);
	}
	
	protected String getFilename(CodeContext ctx) {
		return PlaceHolderHelper.replace(filename, ctx.getCtxMap());
	}
    
    public boolean isOverride() {
        return override;
    }
    public void setOverride(boolean override) {
        this.override = override;
    }
    public boolean isAppend() {
        return append;
    }
    public void setAppend(boolean append) {
        this.append = append;
    }
    
    public boolean isOverridable() {
        return overridable;
    }
    
    public void setOverridable(boolean overridable) {
        this.overridable = overridable;
    }
}
